var biz_type = "water";
var biz_type_name = "水费";
var city = "";
var province = "";
var uniqu_key = "";
var billKey_lable = "";
var amount;//金额
var bill_user_name;//户名
var access_token="ae9111cd-fbd1-489c-8a63-588010d231b7";
var term_mac="76006DF26D1D4B109EA7E458A95A4FE8";
var term_id="T0000011";

var strInputElement="";
var prefixLetterArray=["A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","W","X","Y","Z"];

var popupPage = "pop_up_shui_index";
var strBtnPopUp = "#btn_pop_" + popupPage;

var strbillKey = "";
var strPhone = "";
var strbillUserName = "";
var strbillDate = "";
var strCharge_inst_name = "";

//支付模块
var paytype="";
var type="";
var trade_no="";
var money="";
var strs=[];
var pay_result="";
$(document).ready(function(){
	term_id = window.CallCSharpMethod("getWebBrowerVariables", "term_id");
	access_token = window.CallCSharpMethod("getWebBrowerVariables", "access_token");
	term_mac = window.CallCSharpMethod("getWebBrowerVariables", "term_mac");
	$("#check_code_url").hide();
	$("#payItem img").click(function(){
		$("img#shui").attr("src","images/shui.png");
		$("img#dian").attr("src","images/dian.png");
		$("img#ran").attr("src","images/ran.png");
		payItemClick(this);
	});

	//选择缴费中心选择点击事件注册
	$("#selPay").click(function(){
		popUPDialog(this);
	});
	$("#orderSubmit").click(function(){
		orderSubmit_click();
	});
	$("#payDiv").click(function() {
		open();
	});
});

function initCityIndex(){
	$("#cityIndex").empty();
	//热门
	var html_hot = '<div class="div_2_2_x">'
		+'            <a href="city_choose_new.jsp#hot" target="show">'
		+'              <label>热门</label>'
		+'            </a>'
		+'          </div>';
    $("#cityIndex").append(html_hot);
	//绘制城市索引
	$(prefixLetterArray).each(function(index,val){
		var html = '<div class="div_2_2_x">'
		    +'         <a href="city_choose_new.jsp#' + val + '" target="show">'
		    +'           <label>' + val + '</label>'
		    +'         </a>'
		    +'      </div>';
    	$("#cityIndex").append(html);
	});
}

function open_sel_province(strElement, strPage){
	$("#province_choose_back").attr("href",strPage);
	strInputElement = strElement;
}

function sel_province_click(province){
	$(strInputElement).val(province);
	$("#province_choose_back").click();
}

function open_sel_city(strElement, strPage){
	$("#city_choose_back").attr("href",strPage);
	strInputElement = strElement;
}

function sel_city_click(city){
	$(strInputElement).val(city);
	$("#city_choose_back").click();
}
function orderSubmit_click(){
	amount = $("#txt_payAmount").val();
	var now=new Date();
	strbillDate = now.getYear() + "-" + now.getMonth();
	strbillUserName = $("#span_bill_user_name").text();
	strbillKey = $("#span_billKey").html();
	//水电煤默认为缴费
	var biz_type_order = "JF";
	var charge_inst = $("#txt_company_h").val();
	strCharge_inst_name = $("#txt_company").val();
	var memo = "水电煤缴费";
	strPhone = $("#txt_phone").val();
	
	var sub_biz_type = biz_type.toUpperCase();
	
	var orderInfo = {
			access_token : access_token,
			term_id : term_id,
			term_mac : term_mac,
			amount : amount,
			bill_date : strbillDate,
			bill_key : strbillKey,
			bill_user_name : strbillUserName,
			biz_type : biz_type_order,
			charge_inst : charge_inst,
			//缴费单位名称 
			charge_inst_name : strCharge_inst_name,
			city : city,
			//备注
			memo : memo,
			phone : strPhone,
			province : province,
			sub_biz_type : sub_biz_type,
			
	};
	var jsonStr = JSON.stringify(orderInfo);
	$.ajax( {  
        type : "post",  
        url : "../ebpp/createBillOrder.do",
        data : {"orderInfo":jsonStr},
        dataType : "json",  
        success : function(json){
        	if(json != null && json.success == "true"){
	        	trade_no = json.trade_no;
	        	//alert("订单创建成功，订单编号:" + trade_no);
	        	paytype = "3";
	        	type = "";
	        	money = amount;
	        	print();
//	        	startPay("3", "", trade_no, amount);
	        	$("#payDiv").trigger("click");
	        	hideLoader();
        	} else {
        		var resultStr = json.result_code_msg;
        		if(resultStr.indexOf("&lt;") > 0){
        			var index = resultStr.indexOf("&lt;");
        			resultStr = json.result_code_msg.substring(0,index);
        		}
        		
        		alertWindow(resultStr, popupPage);
        		$(strBtnPopUp).click();
        	}
        },
		error:function(){
			hideLoader();
//			alert("网络连接错误，请联系管理员");
			alertWindow("网络连接错误，请联系管理员", popupPage);
    		$(strBtnPopUp).click();
		}
    });
}

function check(){
	"use strict"
	$("[id^='label_value_']").each(function(){
		var strbillKey = $(this).siblings("input").val();
		if(strbillKey == ""){
			var str = "请输入" + $(this).html();
			alertWindow(str, popupPage);
			$(strBtnPopUp).click();
			return false;
		}
	});
	strPhone = $("#txt_phone").val();
	if(strPhone == ""){
		var str = "请输入手机号码";
		alertWindow(str, popupPage);
		$(strBtnPopUp).click();
		return false;
	} else if(!checkPhone(strPhone)){
		var str = "请检查手机号码";
		alertWindow(str, popupPage);
		$(strBtnPopUp).click();
		return false;
	} else if($("#check_code").val() == ""){
		var str = "请输入验证码";
		alertWindow(str, popupPage);
		$(strBtnPopUp).click();
		return false;
	}
	return true;
}

//提交订单查询条件，获取缴费订单
function a_sure_click(){
	var bill_query_json_array = new Array();
	if(check()){
		showLoader();
		$("[id^='label_value_']").each(function(){
			var label = $(this).html();
			var name = $(this).attr("name");
			var type = "text";
			var value = $(this).siblings("input").val();
			var bill_query_json = {
					label : label,
					name : name,
					type : type,
					value : value
			};
			bill_query_json_array.push(bill_query_json);
		});
		var company = $("#txt_company_h").val();
		var check_code = $("#check_code").val();
		var searchCondition = {
				access_token : access_token,
				biz_type : biz_type,
				check_code : check_code,
				city: city,
				company : company,
				province : province,
				bill_query_json : JSON.stringify(bill_query_json_array),
				uniqu_key : uniqu_key
		};
		var jsonStr = JSON.stringify(searchCondition);
		$.ajax( {  
	        type : "post",  
	        url : "../ebpp/getBill.do",
	        data : {"searchCondition":jsonStr},
	        dataType : "json",  
	        success : function(json) {
	        	if(json == null){
	        		alertWindow("系统错误，请联系管理员", popupPage);
	        		$(strBtnPopUp).click();

	        		return false;
	        	}
	        	if(json.success == "true"){
	        		$(json.charge_bill.bills).each(function(){
	        			var billKey = this.bill_key;
	        			bill_user_name = this.bill_user_name; 
	        			$("#span_billKey").text(this.bill_key);
	        			$("#span_bill_user_name").text(bill_user_name);
	        			$("#span_amount").text(this.amount.amount);
	        			$("#span_phone").text($("#txt_phone").val());
	        			hideLoader();
	        		});
	        		window.location.href = "shuidianmei.jsp#sure";
	        	}else{
	        		var resultStr = json.result_code_msg;
	        		if(resultStr.indexOf("&lt;") > 0){
	        			var index = resultStr.indexOf("&lt;");
	        			resultStr = json.result_code_msg.substring(0,index);
	        		}
	        		alertWindow(resultStr, popupPage);
	        		$(strBtnPopUp).click();
	        		hideLoader();
	        		check_code_click();
	        		return false;
	        	}
	        },
			error:function(){
				hideLoader();
        		alertWindow("网络连接错误，请联系管理员", popupPage);
        		$(strBtnPopUp).click();
			}
	    });
	}
}

function showBillData(json){
	var phone = $("#txt_phone").val();
	$("#span_phone").text(phone);
	if(json != null && json.success == "true"){
		
	}
}

//弹出缴费公司选择
function popUPDialog(e){
	$("#popupDialog #popupDialogHeader").html("请选择缴费中心");	
	$("#popupDialog #popupDialogMain").empty();
	getCompany();
}

//加载缴费公司
function getCompany(){
	showLoader();
	//唯一码为20位时间戳
	uniqu_key = new Date().getTime();
	city = $("#city").val();
	province = $("#province").val();
	var searchCondition = {
			access_token : access_token,
			biz_type : biz_type,
			city: city,
			province : province,
			uniqu_key : uniqu_key
	};
	var jsonStr = JSON.stringify(searchCondition);
	$.ajax( {  
        type : "post",  
        url : "../ebpp/getCompany.do",
        data : {"searchCondition":jsonStr},
        dataType : "json",  
        success : function(json) {
        	showCompanyData(json);
        	hideLoader();
        },
		error:function(){
			hideLoader();
    		alertWindow("网络连接错误，请联系管理员", popupPage);
    		$(strBtnPopUp).click();
		}
    });
}

function showCompanyData(json){
	var ele_text = "#txt_company";
	var ele_value = "#txt_company_h";
	var strHtml = "";
	if(json == null){
		alertWindow("网络连接错误，请联系管理员", popupPage);
		$(strBtnPopUp).click();
//		alert("系统错误，请联系管理员");
		return false;
	}
	if(json.success == "true"){
		$(json.companys).each(function(){
			var company_value = this.split("=")[0];
			var company_text = this.split("=")[1];
			strHtml = strHtml +'<li>'
						+'       <a href="" onClick="selval(\''+ ele_text +'\',\''+ ele_value +'\',this); return false;">'
						+'         <span id="a_text">'+ company_text +'</span>'
						+'         <span id="a_value" style="display:none">'+ company_value +'</span>'
						+'       </a>'
						+'     </li>';
		});
	} else if(json.success == "false"){
		var resultStr = json.result_code_msg;
		
		alertWindow(resultStr, popupPage);
		$(strBtnPopUp).click();
		return false;
	}
	$("#popupDialog #popupDialogMain").html(strHtml);
	$("#popupDialog #popupDialogMain").listview('refresh'); 
	
}

//缴费公司选择动作
function selval(ele_text,ele_value, t){
	var strText = $(t).children("#a_text").text();
	var strValue = $(t).children("#a_value").text();
	$(ele_text).val(strText);
	$(ele_value).val(strValue);
	$('#btn_sel_window_back').click();
	//缴费中心赋值时获取（查询缴费机构帐单的查询条件）
	$("#companyFare_args").html("");
	companyFare();
}

//根据不同的缴费项目和缴费公司  加载缴费所需的输入条件
function companyFare(){
	showLoader();
	var company = $("#txt_company_h").val();
	var searchCondition = {
			access_token : access_token,
			biz_type : biz_type,
			company : company,
			uniqu_key : uniqu_key
	};
	var jsonStr = JSON.stringify(searchCondition);
	$.ajax( {  
        type : "post",  
        url : "../ebpp/getCompanyFare.do",
        data : {"searchCondition":jsonStr},
        dataType : "json",  
        success : function(json) {
//        	console.dir(json);
        	showCompanyFareData(json);
        	$("#check_code_url").attr("src",json.check_code_url);
        	$("#check_code_url").show();
        	hideLoader();
        },
		error:function(){
			hideLoader();
//			alert("网络连接错误，请联系管理员");
    		alertWindow("网络连接错误，请联系管理员", popupPage);
    		$(strBtnPopUp).click();
		}
    });
}

function showCompanyFareData(json){
	$("#inputList").empty();
	if(json == null){
		alertWindow("网络连接错误，请联系管理员", popupPage);
		$(strBtnPopUp).click();
//		alert("系统错误，请联系管理员");
		return false;
	}
	if(json.success == "true"){
		
		var fares = json.fares;
		
		for(var i=0;i<fares.length;i++){
			var html = '<div class="sdm_bg1 sdm_bg2">' +
							'<label id="label_value_'+ i +'" name="'+fares[i].name+'" >' + fares[i].label +'</label>'+
							'<input id="txt_billKey_'+ i +'" type="text" data-role="none" maxlength="20"' +
							    'onClick="showKeyboard();" onBlur="hideKeyboard();" />'+ 
				        '</div>';
			$("#companyFare_args").append(html);
		}
	} else if(json.success == "false"){
		var resultStr = json.result_code_msg;
		alert(resultStr);
		return false;
	}
}

//水电煤订单详情页取消按钮动作
function cancel_click(){
	$("#province").val("");
	$("#city").val("");
	$("#txt_company").val("");
	$("#txt_company_h").val("");
	$("#txt_phone").val("");
	$("#check_code").val("");
	$("#check_code_url").hide();
	$("#companyFare_args").html("");
	window.location.href = "shuidianmei.jsp#shui_index";
}

//点击刷新验证码
function check_code_click(){
	updateCheckCode();
}

function updateCheckCode(){
	
	var company = $("#txt_company_h").val();
	var searchCondition = {
			access_token : access_token,
			biz_type : biz_type,
			company : company,
			uniqu_key : uniqu_key
	};
	var jsonStr = JSON.stringify(searchCondition);
	$.ajax( {  
        type : "post",  
        url : "../ebpp/getCompanyFare.do",
        data : {"searchCondition":jsonStr},
        dataType : "json",  
        success : function(json) {
        	if(json != null && json.success == "true"){
	        	$("#check_code_url").attr("src",json.check_code_url);
	    		$("#check_code_url").show();
        	}
        	hideLoader();
        },
		error:function(){
			hideLoader();
//			alert("网络连接错误，请联系管理员");
    		alertWindow("网络连接错误，请联系管理员", popupPage);
    		$(strBtnPopUp).click();
		}
    });
}

function payItemClick(e){
	$("#txt_company").val("");
	$("#txt_company_h").val("");
	$("#companyFare_args").html("");
	if($(e).attr("id") == "shui"){
		$(e).attr("src","images/shui_b.png");
		biz_type = "water";
		biz_type_name = "水费";
		$("#txt_billKey").val("");
		$("#txt_phone").val("");
		$("#check_code").val("");
		$("#biz_type").val("water");
	}
	if($(e).attr("id") == "dian"){
		$(e).attr("src","images/dian_b.png");
		biz_type = "electric";
		biz_type_name = "电费";
		$("#txt_billKey").val("");
		$("#txt_phone").val("");
		$("#check_code").val("");
		$("#biz_type").val("electric");
	}
	if($(e).attr("id") == "ran"){
		$(e).attr("src","images/ran_b.png");
		biz_type = "gas";
		biz_type_name = "燃气费";
		$("#txt_billKey").val("");
		$("#txt_phone").val("");
		$("#check_code").val("");
		$("#biz_type").val("gas");
	}
}
function open(){
	var url = yumeiUrl+"/trade/getPay.do?paytype="+paytype+"&type="+type+"&trade_no="+trade_no+"&money="+money;
	for ( var int = 0; int < strs.length; int++) {
		url = url+"&strs="+strs[int];
	}
//		str = "pay_result,2";
//		window.CallCSharpMethod("setWebBrowerVariables", str);
//	alert(url);
	$.fancybox.open({
		href : url,
		type : 'iframe',
		closeBtn  : true,
		width : 611,
		height : 427,
		padding : 0,
		afterShow : function(){
			this.inner.css({
				overflow : "auto"
			});
		},
		afterClose : function(data){
			pay_result = window.CallCSharpMethod("getWebBrowerVariables", "pay_result");
//			alert("回来了");
//			alert("pay_result:"+pay_result);
			if (pay_result == 1 || pay_result == "1") {
				window.location.href=yumeiUrl+"/mainFrame/main/main.jsp";
			} 
		}
	});
}
function print()
{
	strs.push("业务类型：水电煤缴费　终端号：" + term_id);
	strs.push("--------------------------------------");
	strs.push("订单号　：" + trade_no);
	strs.push("缴费类型：" + biz_type_name);
	strs.push("户号　　：" + bill_key);
	strs.push("户名　　：" + bill_user_name);
	strs.push("缴费金额：" + parseInt(money).toFixed(2));
	strs.push("下单时间：" + slx_FormatDateTime(new Date(),true));
	strs.push("支付金额：" + parseInt(money).toFixed(2));
	strs.push("--------------------------------------");
}